package com.sinodata.bsm.cicp.collector.weblogic9;

import java.util.ArrayList;
import java.util.List;

import javax.management.MBeanServerConnection;
import javax.management.ObjectName;
import javax.management.remote.JMXConnector;

import org.apache.log4j.Logger;

import weblogic.health.HealthState;

import com.sinodata.bsm.cicp.collector.Collector;
import com.sinodata.bsm.cicp.exception.CollectorException;
import com.sinodata.bsm.cicp.util.JmxUtil;
import com.sinodata.bsm.common.vo.ResPropertyValue;

/**
 * 
 * <p>
 * Description: Server采集器
 * </p>
 *
 * @author liulibo
 * @version 1.1

 * <p>
 * History: 
 *
 * Date                     Author         Version     Description
 * ---------------------------------------------------------------------------------
 * Jun 22, 2011 4:31:30 PM  liulibo        1.1.0       To create
 * Nov 8,  2011 3:42:05 PM  liulibo        1.1.1       新增健康状况、操作系统名称、堆空闲百分比、最大堆大小指标。 
 * </p>
 *
 * @since 
 * @see
 */
public class ServersCollector extends Collector {

    private static final Logger logger = Logger.getLogger(ServersCollector.class);

    /**
     * 执行采集
     */
    @Override
    public List<ResPropertyValue> collect(String ip) throws CollectorException {
        List<ResPropertyValue> values = new ArrayList<ResPropertyValue>();
        String[] propMetas = getPropMeta();
        ResPropertyValue propertyValueX = new ResPropertyValue();
        ResPropertyValue.PropValue[] propValues = new ResPropertyValue.PropValue[propMetas.length];
        String serversName = this.getParamMap().get("ServersName").trim();
        String port = this.getParamMap().get("port").trim();
        Object[] result = new Object[14];
        String[] newresult = new String[14];
        ObjectName service;
        JMXConnector connector = null;
        MBeanServerConnection connection = null;
        try {
            connector = JmxUtil.getConnection(ip, Integer.parseInt(port));
            connection = connector.getMBeanServerConnection();
            service = new ObjectName("com.bea:Name=DomainRuntimeService,Type=weblogic.management.mbeanservers.domainruntime.DomainRuntimeServiceMBean");
            Object domainConfiguration = connection.getAttribute(service, "DomainConfiguration");
            String attributeNames[] = new String[] { "Name", "Machine", "ListenPort" };
            ObjectName[] Servers = (ObjectName[]) connection.getAttribute((ObjectName) domainConfiguration, "Servers");
            for (ObjectName objectName : Servers) {
                Object attrValues[] = null;
                attrValues = JmxUtil.getAttribute(connection, objectName, attributeNames);
                if (attrValues != null && attrValues[0].toString().trim().equals(serversName)) {
                    if (attrValues[1] != null && !"".equals(attrValues[1].toString()) && attrValues[1] instanceof ObjectName) {
                        String machineName = ((ObjectName) attrValues[1]).getKeyProperty("Name");
                        //
                        result[0] = machineName;
                    } else {
                        result[0] = ip;
                    }
                    System.arraycopy(attrValues, 2, result, 1, 1);
                }
            }
            String attributeNames1[] = new String[] { "Name", "ListenAddress", "State", "OpenSocketsCurrentCount", "SocketsOpenedTotalCount", "WeblogicVersion", "JVMRuntime", "HealthState" };
            ObjectName[] serverRuntimes = (ObjectName[]) connection.getAttribute(service, "ServerRuntimes");
            for (ObjectName objectName2 : serverRuntimes) {
                Object attrValues[] = null;
                attrValues = JmxUtil.getAttribute(connection, objectName2, attributeNames1);
                if (attrValues != null && attrValues[0].toString().trim().equals(serversName)) {
                    System.arraycopy(attrValues, 1, result, 2, 5);
                    if (attrValues[6] instanceof ObjectName) {
                        //                                         259588096           166525776            6.1      Windows 7      82              518979584
                        String attributeNames2[] = new String[] { "HeapSizeCurrent", "HeapFreeCurrent", "OSVersion", "OSName", "HeapFreePercent", "HeapSizeMax" };
                        Object attrValues1[] = null;
                        attrValues1 = JmxUtil.getAttribute(connection, (ObjectName) attrValues[6], attributeNames2);
                        System.arraycopy(attrValues1, 0, result, 7, 6);
                    }
                    if (attrValues.length >= 8 && attrValues[7] != null && attrValues[7] instanceof HealthState) {
                        HealthState healthState = (HealthState) attrValues[7];
                        int serverHealthState = healthState.getState();
                        String serverHealth = "UNKNOWN";
                        if (serverHealthState == HealthState.HEALTH_OK) {
                            serverHealth = "OK";
                        } else if (serverHealthState == HealthState.HEALTH_WARN) {
                            serverHealth = "WARN";
                        } else if (serverHealthState == HealthState.HEALTH_CRITICAL) {
                            serverHealth = "CRITICAL";
                        } else if (serverHealthState == HealthState.HEALTH_FAILED) {
                            serverHealth = "FAILED";
                        }
                        result[13] = serverHealth;
                    }
                }
            }
        } catch (Exception e) {
            logger.error("failed to collect by ServersCollector", e);
            throw new CollectorException(e);
        } finally {
            JmxUtil.closeConnector(connector);
        }
        for (int i = 0; i < result.length; i++) {
            if (i == 7 || i == 8 || i == 12) {
                if (result[i] != null) {
                    newresult[i] = Double.valueOf(result[i].toString()) + "";
                } else {
                    newresult[i] = "";
                }
            } else if (result[i] != null) {
                newresult[i] = result[i].toString();
            } else {
                newresult[i] = "";
            }
            propValues[i] = ResPropertyValue.createPropValue(newresult[i], propMetas[i]);
        }
        propertyValueX.setValues(propValues);
        values.add(propertyValueX);
        return values;
    }

    /**
     * 采集参数定义
     */
    @Override
    public String[] getParamMeta() {
        return new String[] { "ServersName", "port" };
    }

    /**
     * 采集字段定义
     */
    @Override
    public String[] getPropMeta() {
        //        return new String[] { "Machine", "ListenPort", "State",
        //                "OpenSocketsCurrentCount", "SocketsOpenedTotalCount",
        //                "WeblogicVersion", "JVMRuntime", "HeapSizeCurrent",
        //                "HeapFreeCurrent", "OSVersion", "OSName", "HeapFreePercent",
        //                "HeapSizeMax", "Health" };
        //1,
        return new String[] { "$1", "$2", "$3", "$4", "$5", "$6", "$7", "$8", "$9", "$10", "$11", "$12", "$13", "$14" };
    }

}
